package com.ming.springboot.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;

/**
 * Created by mqsi on 2022/5/24 20:38
 */
public class JwtTokenUtil {
	// 通过当前线程的类加载器获取资源文件
	private static InputStream inputStream = Thread.currentThread().getContextClassLoader()
			.getResourceAsStream("jwt.jks");
	private static PrivateKey privateKey = null;
	private static PublicKey publicKey = null;
	static {
		try {
			// 加载解析秘钥对文件，获取公钥与私钥信息
			KeyStore keyStore = KeyStore.getInstance("JKS");
			keyStore.load(inputStream, "123456".toCharArray());
			privateKey = (PrivateKey)keyStore.getKey("jwt", "123456".toCharArray());
			publicKey = keyStore.getCertificate("jwt").getPublicKey();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 生成Token字符串
	 *
	 * @param subject           用户名
	 * @param expirationSeconds 过期时间秒
	 * @param salt              盐(私钥)
	 */
	public static String generateToken(String subject, int expirationSeconds, String salt) {
		return Jwts.builder()
				.setClaims(null)
				.setSubject(subject)
				.setExpiration(new Date(System.currentTimeMillis() + expirationSeconds * 1000))
//				.signWith(SignatureAlgorithm.HS512, salt)
				// 通过私钥生成token字符串
				.signWith(SignatureAlgorithm.RS512, privateKey)
				.compact();
	}

	/**
	 * 解析Token
	 *
	 * @param token token字符串
	 * @param salt  私钥
	 */
	public static String parseToken(String token, String salt) {
		String subject = null;
		try {
			Claims claims = Jwts.parser()
//					.setSigningKey(salt)
					// 通过公钥解析Token信息
					.setSigningKey(publicKey)
					.parseClaimsJws(token).getBody();
			subject = claims.getSubject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return subject;
	}

	public static void main(String[] args) {
		String subject = "LiSi";
		String token = generateToken(subject, 100, "_secret");
		System.out.println("Token=" + token);
		String username = parseToken(token, "_secret");
		System.out.println("加密前的字符串：" + username);
	}
}
